<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\UploadFileEvent;
use App\Models\V1\BasicMaintainers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Jenssegers\Agent\Facades\Agent;
use Log;

class ImageUploadController extends Controller
{
    /**
     * 上传更新用户头像
     *
     * @param Request $request
     */
    public function uploadAvatar(Request $request)
    {
        // 返回参数数组
        $response = [
            'rspStatus' => false,
            'rspMsg' => '账号[' . $request->input('code') . '],更新个人头像失败！',
            'rspData' => [
                'avatarSrc' => '',
            ],
        ];

        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'avatar/';
            $storagePath .= $request->input('code');

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 在指定目录保存图片（原图）
            $originPath = Storage::disk('public')->put($storagePath, $file);

            // 更新数据库中头像路径
            $success = $this->handleProfile($request->input('flag'), $request->input('code'), asset('storage' . '/' . $originPath));

            if ($success) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '账号[' . $request->input('code') . '],更新个人头像成功！';
                $response['rspData'] = [
                    'originSrc' => asset('storage' . '/' . $originPath),
                ];
                // 更新个人头像成功，触发事件
                event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspData']));

            } else {
                $response['rspMsg'] = '账号[' . $request->input('code') . '],数据库同步更新个人头像失败！';
            }
        }

        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }

    /**
     * 上传维护员的头像
     *
     * @param Request $request
     */
    public function uploadMaintainerAvatar(Request $request)
    {
        // 返回参数数组
        $response = [
            'rspStatus' => false,
            'rspMsg' => '账号[' . $request->input('code') . ']的头像上传失败！',
            'rspData' => [
                'avatarSrc' => '',
            ],
        ];

        if ($request->method() === 'POST') {
            // 获取request中上传文件对象
            $file = $request->file('file');
            // 返回参数数组
            $response = [
                'rspStatus' => false,
                'rspMsg' => '图片[' . $file->getClientOriginalName() . '],上传失败！',
                'rspData' => [
                    'originSrc' => '',
                ],
            ];

            // 存储路径
            $storagePath = 'maintainerAvatar/';
            $storagePath .= $request->input('code');

            // 在指定目录保存图片（原图）
            $originPath = Storage::disk('public')->put($storagePath, $file);

            // 检查文件是否上传成功
            $success = $this->checkFile($originPath);
            if ($success) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片[' . $file->getClientOriginalName() . '],上传成功！';
                $response['rspData'] = [
                    'originSrc' => asset('storage' . '/' . $originPath),
                    'originExt' => $file->getClientOriginalExtension(),
                    'originName' => $file->getClientOriginalName(),
                ];
                // 更新个人头像成功，触发事件
                event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspData']));
            } else {
                $response['rspMsg'] = '图片上传失败';
            }
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 上传变电站图片
     *
     * @param Request $request
     */
    public function uploadSubstationPicture(Request $request)
    {
        // 返回参数数组
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变电站[' . $request->input('code') . ']的图片上传失败！',
            'rspData' => [
                'avatarSrc' => '',
            ],
        ];

        if ($request->method() === 'POST') {
            // 获取request中上传文件对象
            $file = $request->file('file');
            // 返回参数数组
            $response = [
                'rspStatus' => false,
                'rspMsg' => '图片[' . $file->getClientOriginalName() . '],上传失败！',
                'rspData' => [
                    'originSrc' => '',
                ],
            ];

            // 存储路径
            $storagePath = 'substation/';
            $storagePath .= $request->input('code');

            // 在指定目录保存图片（原图）
            $originPath = Storage::disk('public')->put($storagePath, $file);

            // 检查文件是否上传成功
            $success = $this->checkFile($originPath);
            if ($success) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '图片[' . $file->getClientOriginalName() . '],上传成功！';
                $response['rspData'] = [
                    'originSrc' => asset('storage' . '/' . $originPath),
                    'originExt' => $file->getClientOriginalExtension(),
                    'originName' => $file->getClientOriginalName(),
                ];
                // 更新个人头像成功，触发事件
                event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspData']));
            } else {
                $response['rspMsg'] = '图片上传失败';
            }
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }


    /**
     * 上传更新用户头像(使用Image扩展包，暂不使用)
     *
     * @param Request $request
     */
    public function uploadAvatarImage(Request $request)
    {
        // 返回参数数组
        $response = [
            'rspStatus' => false,
            'rspMsg' => '账号[' . $request->input('code') . '],更新个人头像失败！',
            'rspData' => [
                'avatarSrc' => '',
            ],
        ];

        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'avatar/';
            $storagePath .= $request->input('code');

            // 水印图片路径
            $watermarkImg = base_path() . '/public/images/watermark.png';

            // 获取request中上传文件对象
            $file = $request->file('file');
            $fileExtension = $file->getClientOriginalExtension();

            // 在指定目录保存图片（原图）
            $originPath = Storage::disk('public')->put($storagePath, $file);

            // 原图加水印
            $originImg = Image::make(storage_path('app/public/uploads/') . $originPath)
                ->insert($watermarkImg, 'bottom-right', 2, 2)
                ->save(storage_path('app/public/uploads/') . $storagePath . '/' . $request->input('code') . '.' . $fileExtension);

            // 更新数据库中头像路径
            $success = $this->handleProfile($request->input('code'), $request->input('code'), $originImg);

            if ($success) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '账号[' . $request->input('code') . '],更新个人头像成功！';
                $response['rspData'] = [
                    'originSrc' => $originPath,
                ];
            } else {
                $response['rspMsg'] = '账号[' . $request->input('code') . '],数据库同步更新个人头像失败！';
            }
        }

        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }


    /**
     * 数据库更新头像路径
     *
     * @param $flag
     * @param $code
     * @param $originPath
     * @return bool
     */
    private function handleProfile($flag, $code, $originPath)
    {
        // 头像原图路径
        $data = [
            'avatar' => $originPath,
        ];

        $rspObj = false;
        if ($flag) {
            $rspObj = BasicMaintainers::where('code', $code)->update($data);
        }
        return $rspObj;
    }

    protected function checkFile($url)
    {
        // 验证文件已存在
        $exists = Storage::disk('public')->exists($url);
        if ($exists) {
            return true;
        }
        return false;
    }
}
